import json
from bson import json_util
from bson import ObjectId
from datetime import datetime
from src.components.mongodb_handler import MongodbHandler as MongodbHandler
from src.components.redis_handler import RedisHandler
from src.util.ip_util import IpUtil as IpUtil
from src.util.province_city_util import ProvinceCityUtil as ProvinceCityUtil
from src.model.response import Response as Response
from src.constant.http_status import HttpStatus as HttpStatus
from src.config.mongodb_config import MongodbConfig as MongodbConfig


def save_login_log(request):
    """
    添加登录日志
    :param request:
    :return:
    """

    # 连接数据库
    database = MongodbHandler.get_db(MongodbConfig.IP, MongodbConfig.PORT, MongodbConfig.DATABASE)

    param = json.loads(str(request.body, encoding="utf-8"))

    # 获取user_login_log集合
    user_login_log_collection = database.user_login_log
    # 插入用户登录日志
    user_login_log_dict = dict()
    user_login_log_dict['user_id'] = ObjectId(param['userId'])
    user_login_log_dict['create_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    user_login_log_dict['success'] = 1
    user_login_log_dict['description'] = '登录成功'
    user_login_log_dict['ip'] = IpUtil.get_ip(request)
    obj = ProvinceCityUtil.get_province_and_city(user_login_log_dict['ip'])
    user_login_log_dict['province'] = obj['province']
    user_login_log_dict['city'] = obj['city']
    user_login_log_collection.insert_one(user_login_log_dict)
    MongodbHandler.close()

    # 需要先将_id和user_id（ObjectId类型）对象转换为字符串，否则会报错ObjectId无法序列化
    user_login_log_dict['_id'] = json_util.dumps(user_login_log_dict['_id'])
    user_login_log_dict['user_id'] = json_util.dumps(user_login_log_dict['user_id'])
    response = Response(True, HttpStatus.OK, user_login_log_dict, '用户登录日志添加成功')
    return response


def save_api_call_log(request):
    """
    添加接口调用日志
    :param request:
    :return:
    """

    # 连接数据库
    database = MongodbHandler.get_db(MongodbConfig.IP, MongodbConfig.PORT, MongodbConfig.DATABASE)

    param = json.loads(str(request.body, encoding="utf-8"))

    # 获取api_call_log集合
    api_call_log_collection = database.api_call_log
    # 插入用户登录日志
    api_call_log_dict = dict()
    api_call_log_dict['user_id'] = ObjectId(param['userId'])
    api_call_log_dict['url'] = '/api/' + param['url'].split('/api/')[1]
    api_call_log_dict['api_description'] = str(RedisHandler.get(api_call_log_dict['url']), encoding="utf-8")
    api_call_log_dict['header'] = param['header']
    api_call_log_dict['data'] = param['data']
    api_call_log_dict['method'] = param['method']
    api_call_log_dict['ip'] = IpUtil.get_ip(request)
    obj = ProvinceCityUtil.get_province_and_city(api_call_log_dict['ip'])
    api_call_log_dict['province'] = obj['province']
    api_call_log_dict['city'] = obj['city']
    api_call_log_dict['call_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    api_call_log_collection.insert_one(api_call_log_dict)
    MongodbHandler.close()

    # 需要先将_id和user_id（ObjectId类型）对象转换为字符串，否则会报错ObjectId无法序列化
    api_call_log_dict['_id'] = json_util.dumps(api_call_log_dict['_id'])
    api_call_log_dict['user_id'] = json_util.dumps(api_call_log_dict['user_id'])
    response = Response(True, HttpStatus.OK, None, '接口调用日志添加成功')
    return response


def save_page_visit_log(request):
    """
    调用页面访问接口
    :param request:
    :return:
    """

    # 连接数据库
    database = MongodbHandler.get_db(MongodbConfig.IP, MongodbConfig.PORT, MongodbConfig.DATABASE)

    param = json.loads(str(request.body, encoding="utf-8"))

    # 获取page_visit_log集合
    page_visit_log_collection = database.page_visit_log
    # 插入用户登录日志
    page_visit_log_dict = dict()
    page_visit_log_dict['user_id'] = ObjectId(param['userId'])
    page_visit_log_dict['path'] = param['path']
    page_visit_log_dict['name'] = str(RedisHandler.get(page_visit_log_dict['path']), encoding="utf-8")
    # page_visit_log_dict['header'] = param['header']
    # page_visit_log_dict['data'] = param['data']
    # page_visit_log_dict['method'] = param['method']
    page_visit_log_dict['query_string'] = param['queryString']
    page_visit_log_dict['ip'] = IpUtil.get_ip(request)
    obj = ProvinceCityUtil.get_province_and_city(page_visit_log_dict['ip'])
    page_visit_log_dict['province'] = obj['province']
    page_visit_log_dict['city'] = obj['city']
    page_visit_log_dict['call_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    page_visit_log_collection.insert_one(page_visit_log_dict)
    MongodbHandler.close()

    # 需要先将_id和user_id（ObjectId类型）对象转换为字符串，否则会报错ObjectId无法序列化
    page_visit_log_dict['_id'] = json_util.dumps(page_visit_log_dict['_id'])
    page_visit_log_dict['user_id'] = json_util.dumps(page_visit_log_dict['user_id'])
    response = Response(True, HttpStatus.OK, None, '页面访问日志添加成功')
    return response
